<?php
// 微信模板消息发送
namespace app\message\controller;

use think\Controller;
use think\Db;
use think\Request;

class WxMessage
{
    private $access_token;

    public function __construct()
    {
        $this->access_token = get_access_token();
    }

    public function add()
    {
        $url = 'https://api.weixin.qq.com/wxaapi/newtmpl/addtemplate?access_token=' . $this->access_token . '&tid=0Le6DtGqnwzcQxq841bnqFwQmrfsDtqOSVwJQVbBMBQ&kidList=3&sceneDesc=test';
        // $data = [
        // 	'tid' => '0Le6DtGqnwzcQxq841bnqFwQmrfsDtqOSVwJQVbBMBQ',
        // 	'kidList' => 3,
        // 	'sceneDesc' => 'test'
        // ];
        $res = file_get_contents($url);
        dump($res);
    }

    public function test()
    {
        $url = 'https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate?access_token=' . $this->access_token;
        $res = file_get_contents($url);
        dump($res);
    }

    /**
     * 发送消息（直推比例分佣、级差比例分佣）
     * */
    public function sendProfitMessage($openid = 'oQtYg528FtW2g_pQO2RRyS6I9vBY')
    {
        $template = [
            'touser' => $openid,
            'template_id' => '0Le6DtGqnwzcQxq841bnqFwQmrfsDtqOSVwJQVbBMBQ',
            'miniprogram' => [
                'appid' => C('XCX_APPID'),
                'pagepath' => '/pages/my_income/my_income'
            ],
            //            'scene' => '123',
            //            'title' => 'test标题',
            'data' => array(
                'first' => array('value' => '这个是标题', 'color' => "#173177"),
                'product' => array('value' => '巧克力', 'color' => '#173177'),
                'price' => array('value' => '39.8元', 'color' => '#173177'),
                'time' => array('value' => '2014年9月22日', 'color' => '#173177'),
                'remark' => array('value' => '欢迎再次购买！', 'color' => '#173177'),)
        ];

        $send_template_url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/bizsend?access_token=' . $this->access_token;

        $res = $this->curlRequest($send_template_url, $template);
        echo "<pre>";
        print_r($res);
        exit;
    }

    public function curlRequest($url, $data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }

}
